package com.TeacherInfoServer.converter;

import com.TeacherInfoServer.pojo.entity.TypeInfo;
import com.TeacherInfoServer.common.service.TypeInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Component
@Getter
public class EducatedConverter {

    @Autowired
    private TypeInfoService typeInfoService;
    @Autowired
    @Qualifier("default")
    private RedisTemplate<String,Object> template;
    private List<TypeInfo> typeInfoList = new ArrayList<>();

    public Integer convertToJavaData(String value) {
        if (!typeInfoList.isEmpty()){
            return typeInfoList.stream()
                    .filter(typeInfo -> Objects.equals(typeInfo.getValue(), value))
                    .findFirst()
                    .map(TypeInfo::getId)
                    .orElse(null);
        } else {
            getTypeInfoList();
            return typeInfoList.stream()
                    .filter(typeInfo -> Objects.equals(typeInfo.getValue(), value))
                    .findFirst()
                    .map(TypeInfo::getId)
                    .orElse(null);
        }
    }

    public String convertToExcelData(Integer value) {
        if (!typeInfoList.isEmpty()){
            return typeInfoList.stream()
                    .filter(typeInfo -> Objects.equals(typeInfo.getId(), value))
                    .findFirst()
                    .map(TypeInfo::getValue)
                    .orElse(null);
        } else {
            getTypeInfoList();
            return typeInfoList.stream()
                    .filter(typeInfo -> Objects.equals(typeInfo.getId(), value))
                    .findFirst()
                    .map(TypeInfo::getValue)
                    .orElse(null);
        }
    }

    private void getTypeInfoList() {
        String key = "educated";
        typeInfoList = (List<TypeInfo>) template.opsForValue().get(key);
        if (typeInfoList == null){
            LambdaQueryWrapper<TypeInfo> wrapper = new LambdaQueryWrapper<>();
            typeInfoList = typeInfoService.list(wrapper.eq(TypeInfo::getName,"学历类型"));
            template.opsForValue().set(key,typeInfoList);
        }
    }
}
